package logic

import (
	"context"
	"fmt"
	"models"
	"time"

	"vip_srv/internal/svc"
	"vip_srv/vip_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderRetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderRetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderRetLogic {
	return &OrderRetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderRetLogic) OrderRet(in *vip_srv.OrderRetRequest) (*vip_srv.OrderRetResponse, error) {
	// todo: add your logic here and delete this line
	if in.TradeStatus != "TRADE_SUCCESS" {
		return nil, fmt.Errorf("交易异常")
	}
	var order models.Order
	var log models.Log
	var new_time = time.Now()
	var update_time time.Time
	if err := models.DB.Where("snow = ?", in.OutTradeNo).Limit(1).Find(&order).Error; err != nil {
		return nil, err
	}
	order.Status = "支付成功"
	if err := models.DB.Updates(&order).Error; err != nil {
		return nil, err
	}
	log.OrderId = int64(order.ID)
	log.UserId = order.UserId
	log.PayAt = &new_time
	if err := models.DB.Create(&log).Error; err != nil {
		return nil, err
	}
	key := fmt.Sprintf("vip_%d", order.UserId)
	vip, _ := models.RDB.Get(models.Ctx, key).Int64()
	fmt.Println("会员到期时间时间戳：", vip)
	if vip < new_time.Unix() {
		update_time = new_time.AddDate(0, int(order.AskMonth), 0)
	} else {
		vip_time := time.Unix(vip, 0)
		update_time = vip_time.AddDate(0, int(order.AskMonth), 0)
	}
	models.RDB.Set(models.Ctx, key, update_time.Unix(), 0)
	return &vip_srv.OrderRetResponse{}, nil
}
